package com.bstek.uflo.form.listener;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.jdbc.Work;
import org.springframework.util.StringUtils;

import com.bstek.uflo.command.CommandService;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.Constants;
import com.bstek.uflo.form.model.TableDefinition;
import com.bstek.uflo.form.view.common.FormState;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.listener.ProcessListener;
import com.bstek.uflo.service.ProcessService;

/**
 * @author Jacky.gao
 * @since 2013年11月21日
 */
public class FormProcessListener implements ProcessListener {
	private final Log log=LogFactory.getLog(getClass());
	private CommandService commandService;
	private ProcessService processService;
	public void processStart(ProcessInstance processInstance, Context context) {
	}

	public void processEnd(ProcessInstance processInstance, Context context) {
		String tag=processInstance.getTag();
		if(StringUtils.isEmpty(tag) || !tag.equals(Constants.UFLO_FORM_PROCESS_TAG)){
			return;
		}
		String bussinessId=processInstance.getBusinessId();
		Object id=processService.getProcessVariable(Constants.TABLE_DEF_ID, processInstance.getId());
		if(id==null){
			log.warn("Uflo form process instance was not found table definition id variable.");
			return;
		}
		long tableId=Long.valueOf(id.toString());
		TableDefinition table=(TableDefinition)context.getSession().get(TableDefinition.class, tableId);
		if(table==null){
			log.warn("Table definition "+tableId+" is not exist.");
			return;
		}
		final String sql="update "+table.getName()+" set "+Constants.STATE_COLUMN+"=? where "+Constants.PRIMARY_KEY_COLUMN+"=?";
		final Object[] params=new Object[2];
		params[0]=FormState.Completed.toString();
		params[1]=Long.valueOf(bussinessId);
		context.getSession().doWork(new Work(){
			public void execute(Connection connection) throws SQLException {
				PreparedStatement stmt=connection.prepareStatement(sql);
				stmt.setString(1, params[0].toString());
				stmt.setLong(2, (Long)params[1]);
				stmt.execute();
				stmt.close();
			}
		});
	}

	public CommandService getCommandService() {
		return commandService;
	}

	public void setCommandService(CommandService commandService) {
		this.commandService = commandService;
	}

	public ProcessService getProcessService() {
		return processService;
	}

	public void setProcessService(ProcessService processService) {
		this.processService = processService;
	}
}
